#!/bin/sh /etc/rc.common

START=50
USE_PROCD=1

append_arg() {
  local cfg="$1"
  local var="$2"
  local opt="$3"
  local def="$4"
  local val

  config_get val "$cfg" "$var"
  [ -n "$val" -o -n "$def" ] && procd_append_param command $opt "${val:-$def}"
}

start_instance() {
  local cfg="$1"
  local aux
  local use_config_file

  config_get_bool aux "$cfg" 'disabled' '0'
  [ "$aux" = 1 ] && return 1

  config_get_bool use_config_file "$cfg" 'use_config_file' '0'

  procd_open_instance

  procd_set_param command /usr/bin/rtp2httpd

  # If use_config_file is enabled, don't use --noconfig and let it read /etc/rtp2httpd.conf
  if [ "$use_config_file" = "0" ]; then
    procd_append_param command "--noconfig"

        append_arg "$cfg" verbose "--verbose"
        append_arg "$cfg" port "--listen"
        append_arg "$cfg" upstream_interface_unicast "--upstream-interface-unicast"
        append_arg "$cfg" upstream_interface_multicast "--upstream-interface-multicast"
        append_arg "$cfg" maxclients "--maxclients"
        append_arg "$cfg" workers "--workers"
        append_arg "$cfg" buffer_pool_max_size "--buffer-pool-max-size"
        append_arg "$cfg" hostname "--hostname"
        append_arg "$cfg" status_page_path "--status-page-path"
        append_arg "$cfg" r2h_token "--r2h-token"
        append_arg "$cfg" mcast_rejoin_interval "--mcast-rejoin-interval"
        append_arg "$cfg" fcc_nat_traversal "--fcc-nat-traversal"
        append_arg "$cfg" fcc_listen_port_range "--fcc-listen-port-range"
        append_arg "$cfg" ffmpeg_path "--ffmpeg-path"
        append_arg "$cfg" ffmpeg_args "--ffmpeg-args"

        # Handle video_snapshot flag
        config_get_bool aux "$cfg" 'video_snapshot' '0'
        [ "$aux" = 1 ] && procd_append_param command "--video-snapshot"
  fi

  config_get_bool aux "$cfg" 'respawn' '0'
  [ "$aux" = 1 ] && procd_set_param respawn

  config_get config_update_time "$cfg" 'config_update_time' '0'
  [ "$config_update_time" != 0 ] && procd_set_param env CONFIG_UPDATE_TIME=$config_update_time

  procd_set_param stdout 1
  procd_set_param stderr 1

  procd_close_instance
}

service_triggers() {
  procd_add_reload_trigger "rtp2httpd"
}

start_service() {
  config_load rtp2httpd
  config_foreach start_instance rtp2httpd
}
